<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <!-- 搜索 -->
      <el-input v-model="query.value" clearable placeholder="输入搜索内容" style="width: 200px;" class="filter-item" @keyup.enter.native="toQuery"/>
      <el-select v-model="query.type" clearable placeholder="类型" class="filter-item" style="width: 130px">
        <el-option v-for="item in queryTypeOptions" :key="item.key" :label="item.display_name" :value="item.key"/>
      </el-select>
      <el-button class="filter-item" size="mini" type="success" icon="el-icon-search" @click="toQuery">搜索</el-button>
      <!-- 新增 -->
      <div style="display: inline-block;margin: 0px 2px;">
        <el-button
          class="filter-item"
          size="mini"
          type="primary"
          icon="el-icon-plus"
          @click="add">新增</el-button>
      </div>
      <!-- 导出 -->
      <div style="display: inline-block;">
        <el-button
          :loading="downloadLoading"
          size="mini"
          class="filter-item"
          type="warning"
          icon="el-icon-download"
          @click="download">导出</el-button>
      </div>
    </div>
    <!--表单组件-->
    <eForm ref="form" :is-add="isAdd"/>
    <el-row :gutter="15">
      <!--角色管理-->
      <el-col :xs="12" :sm="12" :md="12" :lg="14" :xl="14" style="margin-bottom: 10px">
        <el-card class="box-card" shadow="never">
          <div slot="header" class="clearfix">
            <span class="role-span">项目列表</span>
          </div>
          <!--表格渲染-->
          <el-table v-loading="loading" ref="projectTable" :data="data" highlight-current-row row-key="id" size="small" style="width: 100%;" @current-change="handleCurrentChange">
            <el-table-column prop="id" label="编号"/>
            <el-table-column prop="name" label="项目名称"/>
            <el-table-column prop="description" label="项目描述"/>
            <el-table-column prop="ceated" label="创建时间" show-overflow-tooltip/>
            <el-table-column prop="amount" label="项目资金"/>
            <el-table-column prop="income" label="项目收益"/>
            <el-table-column v-if="checkPermission(['admin','project:edit','project:del'])" label="操作" width="150px" align="center">
              <template slot-scope="scope">
                <el-button size="mini" type="primary" icon="el-icon-edit" @click="edit(scope.row)"/>
                <el-popover
                  :ref="scope.row.id"
                  placement="top"
                  width="180">
                  <p>确定删除本条数据吗？</p>
                  <div style="text-align: right; margin: 0">
                    <el-button size="mini" type="text" @click="$refs[scope.row.id].doClose()">取消</el-button>
                    <el-button :loading="delLoading" type="primary" size="mini" @click="subDelete(scope.row.id)">确定</el-button>
                  </div>
                  <el-button slot="reference" type="danger" icon="el-icon-delete" size="mini"/>
                </el-popover>
              </template>
            </el-table-column>
          </el-table>
          <!--分页组件-->
          <el-pagination
            :total="total"
            :current-page="page + 1"
            style="margin-top: 8px;"
            layout="total, prev, pager, next, sizes"
            @size-change="sizeChange"
            @current-change="pageChange"/>
        </el-card>
      </el-col>
      <el-col :xs="12" :sm="12" :md="12" :lg="10" :xl="10">
        <el-card class="box-card" shadow="never" style="margin-bottom: 15px;">
          <div slot="header" class="clearfix">
            <el-tooltip class="item" effect="dark" content="选择指定员工分配项目" placement="top">
              <span class="role-span">项目分配</span>
            </el-tooltip>
            <el-button :disabled="!showButton" :loading="menuLoading" icon="el-icon-check" size="mini" style="float: right; padding: 6px 9px" type="primary" @click="saveTable">保存</el-button>
          </div>
          <el-table v-loading="loading" ref="multipleTable" :data="userlist" size="small" max-height="315" style="width: 100%;" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55"/>
            <el-table-column prop="employeename" label="姓名" align="center">
              <template slot-scope="scope">
                <el-tooltip :content="scope.row.dept.name + `/` + scope.row.job.name" class="item" effect="dark" placement="top">
                  <span>{{ scope.row.employeename }}</span>
                </el-tooltip>
              </template>
            </el-table-column>
            <el-table-column prop="type" label="分成类型" align="center" width="350">
              <template slot-scope="scope">
                <el-radio-group v-model="scope.row.type">
                  <el-radio label="count">订单数量</el-radio>
                  <el-radio label="amount">订单金额</el-radio>
                  <el-radio label="profit">毛利润</el-radio>
                </el-radio-group>
              </template>
            </el-table-column>
            <el-table-column label="提成(%)" align="center" width="100">
              <template slot-scope="scope">
                <el-input v-model="scope.row.commission" placeholder="比例" maxlength="2"/>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
        <el-card class="box-card" shadow="never">
          <div slot="header" class="clearfix">
            <el-tooltip class="item" effect="dark" content="选择指定员工分配净利润" placement="top">
              <span class="role-span">净利润分配</span>
            </el-tooltip>
            <el-button :disabled="!showButton" :loading="menuLoading" icon="el-icon-check" size="mini" style="float: right; padding: 6px 9px" type="primary" @click="saveDividendTable">保存</el-button>
          </div>
          <el-table v-loading="loading" ref="dividendTable" :data="userlist" size="small" max-height="315" style="width: 100%;" @selection-change="dividendSelectionChange">
            <el-table-column type="selection" width="55"/>
            <el-table-column prop="employeename" label="姓名" align="center" width="114"/>
            <el-table-column label="部门/岗位" align="center">
              <template slot-scope="scope">
                <div>{{ scope.row.dept.name }} / {{ scope.row.job.name }}</div>
              </template>
            </el-table-column>
            <el-table-column label="提成(%)" align="center" width="100">
              <template slot-scope="scope">
                <el-input v-model="scope.row.dividend" placeholder="比例" maxlength="2"/>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import checkPermission from '@/utils/permission'
import initData from '@/mixins/initData'
import { del, downloadProject, editUser, editDividend } from '@/api/project'
import { getUsers } from '@/api/user'
import { downloadFile } from '@/utils/index'
import { get } from '@/api/role'
import eForm from './form'
export default {
  components: { eForm },
  mixins: [initData],
  data() {
    return {
      delLoading: false, userlist: [], selectionList: [], dividendSelectionList: [], menuIds: [], currentRow: {}, currentId: 0, menuLoading: false, showButton: false,
      queryTypeOptions: [
        { key: 'name', display_name: '项目名称' }
      ]
    }
  },
  created() {
    this.getUserslist()
    this.$nextTick(() => {
      this.init()
    })
  },
  methods: {
    checkPermission,
    beforeInit() {
      this.showButton = false
      this.url = 'api/project'
      const sort = 'id,desc'
      this.params = { page: this.page, size: this.size, sort: sort }
      const query = this.query
      const type = query.type
      const value = query.value
      if (type && value) { this.params[type] = value }
      // 清空菜单的选中
      this.$refs.multipleTable.clearSelection()
      return true
    },
    getUserslist() {
      getUsers().then(res => {
        this.userlist = res
        this.userlist.forEach(val => {
          this.$set(val, 'commission', '')
          this.$set(val, 'type', '')
          this.$set(val, 'dividend', '')
        })
      })
    },
    subDelete(id) {
      this.delLoading = true
      del(id).then(res => {
        this.delLoading = false
        this.$refs[id].doClose()
        this.dleChangePage()
        this.init()
        this.$notify({
          title: '删除成功',
          type: 'success',
          duration: 2500
        })
      }).catch(err => {
        this.delLoading = false
        this.$refs[id].doClose()
        console.log(err.response.data.message)
      })
    },
    add() {
      this.isAdd = true
      this.$refs.form.dialog = true
    },
    edit(data) {
      this.isAdd = false
      const _this = this.$refs.form
      _this.form = {
        id: data.id,
        name: data.name,
        description: data.description,
        ceated: data.ceated,
        amount: data.amount,
        income: data.income
      }
      _this.dialog = true
    },
    // 导出
    download() {
      this.beforeInit()
      this.downloadLoading = true
      downloadProject(this.params).then(result => {
        downloadFile(result, 'Project列表', 'xlsx')
        this.downloadLoading = false
      }).catch(() => {
        this.downloadLoading = false
      })
    },
    handleCurrentChange(val) {
      console.log(val.userProject, val.userDividend)
      const _this = this
      // 清空菜单的选中
      this.$refs.multipleTable.clearSelection()
      _this.$refs.dividendTable.clearSelection()
      this.currentRow = val
      // 保存当前的角色id
      this.currentId = val.id
      // 点击后显示按钮
      this.showButton = true
      if (val.userProject) {
        _this.userlist.forEach(function(data, index) {
          data.commission = ''
          data.type = ''
          val.userProject.forEach(row => {
            if (data.id === row.uid) {
              _this.$refs.multipleTable.toggleRowSelection(data)
              data.commission = row.commission
              data.type = row.type
            }
          })
        })
      } else {
        _this.$refs.multipleTable.clearSelection()
      }
      if (val.userDividend) {
        _this.userlist.forEach(function(data, index) {
          data.dividend = ''
          val.userDividend.forEach(row => {
            if (data.id === row.uid) {
              _this.$refs.dividendTable.toggleRowSelection(data)
              data.dividend = row.commission
            }
          })
        })
      } else {
        _this.$refs.dividendTable.clearSelection()
      }
    },
    handleSelectionChange(val) {
      this.selectionList = val
    },
    dividendSelectionChange(val) {
      this.dividendSelectionList = val
    },
    saveTable() {
      const _this = this
      this.menuLoading = true
      const role = _this.currentRow
      role.userProject = []
      _this.selectionList.forEach(function(data, index) {
        role.userProject.push({
          uid: data.id,
          pid: _this.currentId,
          commission: data.commission || 1,
          type: data.type
        })
      })
      console.log(`role：`, role)
      editUser(role).then(res => {
        this.$notify({
          title: '保存成功',
          type: 'success',
          duration: 2500
        })
        this.menuLoading = false
        // this.update()
      }).catch(err => {
        this.menuLoading = false
        console.log(err.response.data.message)
      })
    },
    saveDividendTable() {
      const _this = this
      this.menuLoading = true
      const role = _this.currentRow
      role.userDividend = []
      _this.dividendSelectionList.forEach(function(data, index) {
        role.userDividend.push({
          uid: data.id,
          pid: _this.currentId,
          commission: data.dividend || 1
        })
      })
      console.log(`role：`, role)
      editDividend(role).then(res => {
        this.$notify({
          title: '保存成功',
          type: 'success',
          duration: 2500
        })
        this.menuLoading = false
        // this.update()
      }).catch(err => {
        this.menuLoading = false
        console.log(err.response.data.message)
      })
    },
    update() {
      // 无刷新更新 表格数据
      get(this.currentId).then(res => {
        for (let i = 0; i < this.data.length; i++) {
          if (res.id === this.data[i].id) {
            this.data[i] = res
            break
          }
        }
      })
    }
  }
}
</script>

<style scoped>
</style>
